package org.example.rsy.service;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.example.rsy.exception.TikaException;
import org.xml.sax.ContentHandler;

import java.io.InputStream;

public abstract class BaseTikaService implements ITikaService {


    private Parser parser;

    private ContentHandler handler;

    private Metadata metadata;

    @Override
    public String parse(InputStream inputStream) throws TikaException {
        this.parser = initParse();
        this.handler = initHandler();
        this.metadata = initMetadata();
        try {
            parser.parse(inputStream, handler, metadata, new ParseContext());
        } catch (Exception e) {
            throw new TikaException(e);
        }
        return extractData();
    }

    public Metadata initMetadata() {
        return new Metadata();
    }

    public ContentHandler initHandler() {
        return new BodyContentHandler();
    }

    public Parser initParse() {
        return new AutoDetectParser();
    }

    public abstract String extractData();

    public Parser getParser() {
        return parser;
    }

    public void setParser(Parser parser) {
        this.parser = parser;
    }

    public ContentHandler getHandler() {
        return handler;
    }

    public void setHandler(ContentHandler handler) {
        this.handler = handler;
    }

    public Metadata getMetadata() {
        return metadata;
    }

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

}
